using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;
using System.Media;

namespace PinTuGame
{
    public partial class Form1 : Form
    {
        private PuzzleGame game;
        private Button[,] pieceButtons;
        private System.Windows.Forms.Timer gameTimer;
        private int selectedPieceIndex = -1;
                 private bool isPaused = false;
         private bool showHint = false;
         private bool soundEnabled = true;
         private bool isAutoPlaying = false;
         private string currentImageName = "";
        
        // 控件声明
        private ComboBox difficultyComboBox;
        private Button startButton;
                 private Button shuffleButton;
         private Button pauseButton;
         private Button hintButton;
         private Button autoPlayButton;
         private Button settingsButton;
         private Button leaderboardButton;
         private Button exitButton;
        private Label timeLabel;
        private Label movesLabel;
        private PictureBox originalImageBox;
        private Panel gamePanel;
        private Panel controlPanel;
        private Panel previewPanel;
        
        // 音效
        private SoundPlayer moveSound;
        private SoundPlayer completeSound;
        
        // 排行榜
        private Leaderboard leaderboard;

        public Form1()
        {
            InitializeComponent();
            InitializeUIComponents();
            InitializeGameControls();
            LoadSounds();
            leaderboard = new Leaderboard();
        }

        private void InitializeUIComponents()
        {
            this.Size = new Size(1200, 800);
            this.Text = "拼图游戏";
            this.StartPosition = FormStartPosition.CenterScreen;

            // 创建主布局面板
            TableLayoutPanel mainLayout = new TableLayoutPanel
            {
                Dock = DockStyle.Fill,
                ColumnCount = 2,
                RowCount = 1,
                ColumnStyles = 
                {
                    new ColumnStyle(SizeType.Percent, 70),
                    new ColumnStyle(SizeType.Percent, 30)
                }
            };

            // 左侧游戏区域
            gamePanel = new Panel
            {
                Dock = DockStyle.Fill,
                BackColor = Color.LightGray
            };

            // 右侧控制面板
            controlPanel = new Panel
            {
                Dock = DockStyle.Fill,
                BackColor = Color.WhiteSmoke
            };

            mainLayout.Controls.Add(gamePanel, 0, 0);
            mainLayout.Controls.Add(controlPanel, 1, 0);
            this.Controls.Add(mainLayout);

            // 初始化游戏区域控件
            InitializeGamePanel();

            // 初始化控制面板
            InitializeControlPanel();
        }

        private void InitializeGamePanel()
        {
            // 游戏区域标题
            Label gameTitleLabel = new Label
            {
                Text = "拼图游戏区域",
                Font = new Font("微软雅黑", 14, FontStyle.Bold),
                TextAlign = ContentAlignment.MiddleCenter,
                Dock = DockStyle.Top,
                Height = 40,
                BackColor = Color.LightBlue
            };
            gamePanel.Controls.Add(gameTitleLabel);
        }

        private void InitializeControlPanel()
        {
            // 控制面板标题
            Label controlTitleLabel = new Label
            {
                Text = "游戏控制",
                Font = new Font("微软雅黑", 12, FontStyle.Bold),
                TextAlign = ContentAlignment.MiddleCenter,
                Dock = DockStyle.Top,
                Height = 30,
                BackColor = Color.LightGreen
            };
            controlPanel.Controls.Add(controlTitleLabel);

            // 创建控制面板的滚动面板
            Panel scrollPanel = new Panel
            {
                Dock = DockStyle.Fill,
                AutoScroll = true
            };
            controlPanel.Controls.Add(scrollPanel);

            int yOffset = 10;

            // 难度选择
            Label difficultyLabel = new Label
            {
                Text = "难度选择:",
                Location = new Point(10, yOffset),
                AutoSize = true,
                Font = new Font("微软雅黑", 9)
            };
            scrollPanel.Controls.Add(difficultyLabel);
            yOffset += 25;

            difficultyComboBox = new ComboBox
            {
                Location = new Point(10, yOffset),
                Width = 150,
                DropDownStyle = ComboBoxStyle.DropDownList,
                Font = new Font("微软雅黑", 9)
            };
            difficultyComboBox.Items.AddRange(new object[] { "10×10", "20×20", "30×30", "40×40", "50×50" });
            difficultyComboBox.SelectedIndexChanged += difficultyComboBox_SelectedIndexChanged;
            scrollPanel.Controls.Add(difficultyComboBox);
            yOffset += 40;

            // 开始游戏按钮
            startButton = new Button
            {
                Text = "开始游戏",
                Location = new Point(10, yOffset),
                Width = 150,
                Height = 35,
                Font = new Font("微软雅黑", 10, FontStyle.Bold),
                BackColor = Color.LightGreen
            };
             startButton.Click += startButton_Click;
             scrollPanel.Controls.Add(startButton);
             yOffset += 45;
 
             // 打乱拼图按钮
             shuffleButton = new Button
             {
                 Text = "打乱拼图",
                 Location = new Point(10, yOffset),
                 Width = 150,
                 Height = 35,
                 Font = new Font("微软雅黑", 10),
                 BackColor = Color.Orange,
                 Enabled = false
             };
             shuffleButton.Click += shuffleButton_Click;
             scrollPanel.Controls.Add(shuffleButton);
             yOffset += 45;

            // 暂停/继续按钮
            pauseButton = new Button
            {
                Text = "暂停",
                Location = new Point(10, yOffset),
                Width = 150,
                Height = 35,
                Font = new Font("微软雅黑", 10),
                BackColor = Color.LightYellow,
                Enabled = false
            };
            pauseButton.Click += pauseButton_Click;
            scrollPanel.Controls.Add(pauseButton);
            yOffset += 45;

            // 提示按钮
            hintButton = new Button
            {
                Text = "显示提示",
                Location = new Point(10, yOffset),
                Width = 150,
                Height = 35,
                Font = new Font("微软雅黑", 10),
                BackColor = Color.LightCyan,
                Enabled = false
            };
                         hintButton.Click += hintButton_Click;
             scrollPanel.Controls.Add(hintButton);
             yOffset += 45;

             // 自动演示按钮
             autoPlayButton = new Button
             {
                 Text = "自动演示",
                 Location = new Point(10, yOffset),
                 Width = 150,
                 Height = 35,
                 Font = new Font("微软雅黑", 10),
                 BackColor = Color.DarkBlue,
                 Enabled = false
             };
             autoPlayButton.Click += autoPlayButton_Click;
             scrollPanel.Controls.Add(autoPlayButton);
             yOffset += 45;

            // 设置按钮
            settingsButton = new Button
            {
                Text = "游戏设置",
                Location = new Point(10, yOffset),
                Width = 150,
                Height = 35,
                Font = new Font("微软雅黑", 10),
                BackColor = Color.DarkGreen
            };
            settingsButton.Click += settingsButton_Click;
            scrollPanel.Controls.Add(settingsButton);
            yOffset += 45;

            // 排行榜按钮
            leaderboardButton = new Button
            {
                Text = "排行榜",
                Location = new Point(10, yOffset),
                Width = 150,
                Height = 35,
                Font = new Font("微软雅黑", 10),
                BackColor = Color.DarkRed
            };
            leaderboardButton.Click += leaderboardButton_Click;
            scrollPanel.Controls.Add(leaderboardButton);
            yOffset += 45;

            // 退出按钮
            exitButton = new Button
            {
                Text = "退出游戏",
                Location = new Point(10, yOffset),
                Width = 150,
                Height = 35,
                Font = new Font("微软雅黑", 10),
                BackColor = Color.LightCoral
            };
            exitButton.Click += exitButton_Click;
            scrollPanel.Controls.Add(exitButton);
            yOffset += 50;

            // 游戏信息显示
            Label infoLabel = new Label
            {
                Text = "游戏信息",
                Location = new Point(10, yOffset),
                AutoSize = true,
                Font = new Font("微软雅黑", 10, FontStyle.Bold)
            };
            scrollPanel.Controls.Add(infoLabel);
            yOffset += 25;

            timeLabel = new Label
            {
                Text = "时间: 00:00",
                Location = new Point(10, yOffset),
                AutoSize = true,
                Font = new Font("微软雅黑", 9)
            };
            scrollPanel.Controls.Add(timeLabel);
            yOffset += 20;

            movesLabel = new Label
            {
                Text = "步数: 0",
                Location = new Point(10, yOffset),
                AutoSize = true,
                Font = new Font("微软雅黑", 9)
            };
            scrollPanel.Controls.Add(movesLabel);
            yOffset += 30;

            // 原图预览区域
            Label previewLabel = new Label
            {
                Text = "原图预览",
                Location = new Point(10, yOffset),
                AutoSize = true,
                Font = new Font("微软雅黑", 10, FontStyle.Bold)
            };
            scrollPanel.Controls.Add(previewLabel);
            yOffset += 25;

            originalImageBox = new PictureBox
            {
                Location = new Point(10, yOffset),
                Size = new Size(150, 150),
                SizeMode = PictureBoxSizeMode.Zoom,
                BorderStyle = BorderStyle.FixedSingle,
                BackColor = Color.White
            };
            scrollPanel.Controls.Add(originalImageBox);
            
            // 设置按钮文字颜色
            SetButtonTextColors();
        }
        
        /// <summary>
        /// 设置按钮文字颜色，深色背景使用白色文字
        /// </summary>
        private void SetButtonTextColors()
        {
            // 定义所有按钮
            var allButtons = new[] { startButton, shuffleButton, pauseButton, hintButton, autoPlayButton, settingsButton, leaderboardButton, exitButton };
            
            foreach (var button in allButtons)
            {
                if (button != null)
                {
                    // 计算背景色的亮度
                    Color bgColor = button.BackColor;
                    double brightness = (0.299 * bgColor.R + 0.587 * bgColor.G + 0.114 * bgColor.B) / 255.0;
                    
                    // 如果亮度小于0.5，认为是深色背景，使用白色文字
                    if (brightness < 0.5)
                    {
                        button.ForeColor = Color.White;
                    }
                }
            }
        }

        private void InitializeGameControls()
        {
            // 初始化游戏计时器
            gameTimer = new System.Windows.Forms.Timer { Interval = 1000 };
            gameTimer.Tick += GameTimer_Tick;
            
            // 设置默认难度
            difficultyComboBox.SelectedIndex = 0;
        }

        private void LoadSounds()
        {
            try
            {
                // 这里可以加载音效文件，暂时使用系统音效
                moveSound = new SoundPlayer();
                completeSound = new SoundPlayer();
            }
            catch (Exception ex)
            {
                // 音效加载失败时禁用音效
                soundEnabled = false;
                Console.WriteLine($"音效加载失败: {ex.Message}");
            }
        }

        private void PlayMoveSound()
        {
            if (soundEnabled)
            {
                try
                {
                    SystemSounds.Asterisk.Play();
                }
                catch { }
            }
        }

        private void PlayCompleteSound()
        {
            if (soundEnabled)
            {
                try
                {
                    SystemSounds.Exclamation.Play();
                }
                catch { }
            }
        }

        private void GameTimer_Tick(object sender, EventArgs e)
        {
            if (!isPaused)
            {
                UpdateGameInfo();
            }
        }

        private void UpdateGameInfo()
        {
            timeLabel.Text = $"时间: {game?.PlayTime:mm\\:ss}";
            movesLabel.Text = $"步数: {game?.MoveCount ?? 0}";
        }

        private void startButton_Click(object sender, EventArgs e)
        {
            // 打开文件对话框选择图片
            using (OpenFileDialog openFileDialog = new OpenFileDialog())
            {
                openFileDialog.Filter = "图片文件|*.jpg;*.jpeg;*.png;*.bmp";
                if (openFileDialog.ShowDialog() == DialogResult.OK)
                {
                    try
                    {
                        Image image = Image.FromFile(openFileDialog.FileName);
                        StartNewGame(image);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show($"加载图片失败: {ex.Message}", "错误", 
                            MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
        }

        private void StartNewGame(Image image)
        {
            // 解析难度设置
            PuzzleGame.Difficulty difficulty = difficultyComboBox.SelectedIndex switch
            {
                0 => PuzzleGame.Difficulty.Easy,    // 10x10
                1 => PuzzleGame.Difficulty.Medium,  // 20x20
                2 => PuzzleGame.Difficulty.Hard,    // 30x30
                3 => PuzzleGame.Difficulty.Extreme, // 40x40
                4 => PuzzleGame.Difficulty.Insane,  // 50x50
                _ => PuzzleGame.Difficulty.Easy
            };

            // 计算适合游戏区域的图片尺寸
            Size scaledImageSize = CalculateOptimalImageSize(image, difficulty);
            
            // 创建缩放后的图片
            Image scaledImage = ResizeImage(image, scaledImageSize);

                         // 初始化游戏（不自动打乱）
             game = new PuzzleGame(difficulty);
             game.NewGameWithoutShuffle(scaledImage);
            
            // 保存图片名称
            currentImageName = System.IO.Path.GetFileNameWithoutExtension(image.ToString());
            
            // 显示原图预览（使用缩放后的图片）
            originalImageBox.Image = new Bitmap(scaledImage, originalImageBox.Size);
            
            // 初始化拼图按钮（立即显示乱序的拼图）
            InitializePieceButtons();
            
                         // 启用游戏控制按钮
             shuffleButton.Enabled = true;
             pauseButton.Enabled = true;
             hintButton.Enabled = true;
             autoPlayButton.Enabled = true;
            
            // 重置暂停状态
            isPaused = false;
            pauseButton.Text = "暂停";

            // 开始计时
            shuffleButton.PerformClick();
            gameTimer.Start();
            UpdateGameInfo();
            
            // 显示游戏开始提示
            MessageBox.Show("游戏开始！\n\n游戏规则：\n1. 左键选择一个方块\n2. 右键选择另一个方块\n3. 两个方块将交换位置\n4. 将所有方块排列成原图顺序即可获胜", 
                "游戏规则", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        /// <summary>
        /// 计算适合游戏区域的最优图片尺寸
        /// </summary>
        private Size CalculateOptimalImageSize(Image originalImage, PuzzleGame.Difficulty difficulty)
        {
            // 获取游戏区域可用空间
            int gameAreaWidth = gamePanel.Width - 40;  // 留出边距
            int gameAreaHeight = gamePanel.Height - 80; // 留出标题和边距
            
            // 根据难度确定拼图块数量
            int gridSize = difficulty switch
            {
                PuzzleGame.Difficulty.Easy => 10,
                PuzzleGame.Difficulty.Medium => 20,
                PuzzleGame.Difficulty.Hard => 30,
                PuzzleGame.Difficulty.Extreme => 40,
                PuzzleGame.Difficulty.Insane => 50,
                _ => 10
            };
            
            // 计算单个拼图块的最大尺寸
            int maxPieceWidth = gameAreaWidth / gridSize - 5;  // 留出间距
            int maxPieceHeight = gameAreaHeight / gridSize - 5;
            
            // 计算整个拼图的最大尺寸
            int maxPuzzleWidth = maxPieceWidth * gridSize;
            int maxPuzzleHeight = maxPieceHeight * gridSize;
            
            // 计算缩放比例，保持宽高比
            double scaleX = (double)maxPuzzleWidth / originalImage.Width;
            double scaleY = (double)maxPuzzleHeight / originalImage.Height;
            double scale = Math.Min(scaleX, scaleY);
            
            // 如果图片太小，适当放大（但不超过原始尺寸的2倍）
            if (scale > 1.0)
            {
                scale = Math.Min(scale, 2.0);
            }
            
            // 计算最终尺寸
            int finalWidth = (int)(originalImage.Width * scale);
            int finalHeight = (int)(originalImage.Height * scale);
            
            // 确保尺寸是拼图块数量的整数倍
            finalWidth = (finalWidth / gridSize) * gridSize;
            finalHeight = (finalHeight / gridSize) * gridSize;
            
            // 设置最小尺寸
            finalWidth = Math.Max(finalWidth, gridSize * 60);  // 最小60像素每块
            finalHeight = Math.Max(finalHeight, gridSize * 60);
            
            return new Size(finalWidth, finalHeight);
        }

        /// <summary>
        /// 缩放图片到指定尺寸
        /// </summary>
        private Image ResizeImage(Image originalImage, Size newSize)
        {
            // 创建新的位图
            Bitmap resizedImage = new Bitmap(newSize.Width, newSize.Height);
            
            using (Graphics graphics = Graphics.FromImage(resizedImage))
            {
                // 设置高质量插值模式
                graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                graphics.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
                
                // 绘制缩放后的图片
                graphics.DrawImage(originalImage, 0, 0, newSize.Width, newSize.Height);
            }
            
            return resizedImage;
        }

        private string GetPlayerName()
        {
            Form inputForm = new Form
            {
                Text = "输入玩家名称",
                Size = new Size(300, 150),
                StartPosition = FormStartPosition.CenterParent,
                FormBorderStyle = FormBorderStyle.FixedDialog,
                MaximizeBox = false,
                MinimizeBox = false
            };

            Label label = new Label
            {
                Text = "请输入您的姓名:",
                Location = new Point(20, 20),
                AutoSize = true
            };

            TextBox textBox = new TextBox
            {
                Location = new Point(20, 50),
                Width = 250,
                Text = "玩家"
            };

            Button okButton = new Button
            {
                Text = "确定",
                Location = new Point(100, 80),
                DialogResult = DialogResult.OK
            };

            Button cancelButton = new Button
            {
                Text = "取消",
                Location = new Point(180, 80),
                DialogResult = DialogResult.Cancel
            };

            inputForm.Controls.AddRange(new Control[] { label, textBox, okButton, cancelButton });
            inputForm.AcceptButton = okButton;

            if (inputForm.ShowDialog() == DialogResult.OK)
            {
                return textBox.Text.Trim();
            }

            return "";
        }

        private void InitializePieceButtons()
        {
            // 清除现有按钮
            if (pieceButtons != null)
            {
                foreach (var button in pieceButtons)
                {
                    if (button != null)
                        gamePanel.Controls.Remove(button);
                }
            }

            int size = game.GetBoard().GetLength(0);
            pieceButtons = new Button[size, size];
            
            // 计算按钮大小，留出边距
            int availableWidth = gamePanel.Width - 40;
            int availableHeight = gamePanel.Height - 80;
            int buttonSize = Math.Min(availableWidth / size, availableHeight / size) - 5;
            
            // 计算起始位置，使拼图居中
            int startX = (gamePanel.Width - size * (buttonSize + 5)) / 2;
            int startY = 60;
            
            for (int y = 0; y < size; y++)
            {
                for (int x = 0; x < size; x++)
                {
                    int index = y * size + x;
                    int pieceValue = game.GetBoard()[x, y];
                    
                                         Button button = new Button
                     {
                         Size = new Size(buttonSize, buttonSize),
                         Location = new Point(startX + x * (buttonSize + 5), startY + y * (buttonSize + 5)),
                         Tag = index,
                         BackgroundImage = game.GetPieceImage(pieceValue - 1),
                         BackgroundImageLayout = ImageLayout.Stretch,
                         FlatStyle = FlatStyle.Flat,
                         BackColor = Color.White
                     };
                    
                                         // 禁用右键菜单，确保右键点击能正常工作
                     button.ContextMenuStrip = null;
                     // 使用MouseDown事件处理左右键
                     button.MouseDown += PieceButton_MouseDown;
                    pieceButtons[x, y] = button;
                    gamePanel.Controls.Add(button);
                }
            }
        }

                 private void PieceButton_MouseDown(object sender, MouseEventArgs e)
         {
             if (game == null || game.CurrentState != PuzzleGame.GameState.Playing || isPaused || isAutoPlaying) return;
             
             int clickedIndex = (int)((Button)sender).Tag;
             
             if (e.Button == MouseButtons.Left)
             {
                 // 左键选择第一个方块
                 if (selectedPieceIndex == -1)
                 {
                     selectedPieceIndex = clickedIndex;
                     ((Button)sender).FlatStyle = FlatStyle.Flat;
                     ((Button)sender).FlatAppearance.BorderColor = Color.Red;
                     ((Button)sender).FlatAppearance.BorderSize = 3;
                 }
                 else if (selectedPieceIndex == clickedIndex)
                 {
                     // 再次左键点击同一个方块，取消选择
                     ((Button)sender).FlatStyle = FlatStyle.Flat;
                     ((Button)sender).FlatAppearance.BorderSize = 1;
                     ((Button)sender).FlatAppearance.BorderColor = Color.Gray;
                     selectedPieceIndex = -1;
                 }
             }
             else if (e.Button == MouseButtons.Right)
             {
                 // 右键选择第二个方块进行交换
                 if (selectedPieceIndex != -1 && selectedPieceIndex != clickedIndex)
                 {
                     // 执行交换
                     if (game.SwapPieces(selectedPieceIndex, clickedIndex))
                     {
                         // 交换成功，播放音效
                         PlayMoveSound();
                         
                         // 重置交换方块的背景颜色为未选中状态
                         ResetSwapPiecesBackground(selectedPieceIndex, clickedIndex);
                         
                         // 更新UI
                         UpdatePieceButtons();
                         
                         // 检查游戏是否完成
                         if (game.CheckCompletion())
                         {
                             gameTimer.Stop();
                             PlayCompleteSound();
                             
                             // 获取玩家名称
                             string playerName = GetPlayerName();
                             if (!string.IsNullOrEmpty(playerName))
                             {
                                 // 添加到排行榜
                                 string difficultyText = difficultyComboBox.SelectedItem.ToString();
                                 var record = new GameRecord(playerName, difficultyText, game.PlayTime, game.MoveCount, currentImageName);
                                 leaderboard.AddRecord(record);
                             }
                             
                             MessageBox.Show($"恭喜完成拼图!\n用时: {game.PlayTime:mm\\:ss}\n步数: {game.MoveCount}", 
                                 "游戏完成", MessageBoxButtons.OK, MessageBoxIcon.Information);
                             
                                              // 禁用游戏控制按钮
                 shuffleButton.Enabled = false;
                 pauseButton.Enabled = false;
                 hintButton.Enabled = false;
                 autoPlayButton.Enabled = false;
                         }
                     }
                     
                     // 重置选择状态
                     if (selectedPieceIndex >= 0)
                     {
                         int size = game.GetBoard().GetLength(0);
                         int x = selectedPieceIndex % size;
                         int y = selectedPieceIndex / size;
                         if (pieceButtons[x, y] != null)
                         {
                             pieceButtons[x, y].FlatStyle = FlatStyle.Flat;
                             pieceButtons[x, y].FlatAppearance.BorderSize = 1;
                             pieceButtons[x, y].FlatAppearance.BorderColor = Color.Gray;
                         }
                     }
                     selectedPieceIndex = -1;
                 }
             }
         }

        private void UpdatePieceButtons()
        {
            int size = game.GetBoard().GetLength(0);
            for (int y = 0; y < size; y++)
            {
                for (int x = 0; x < size; x++)
                {
                    int index = y * size + x;
                    int pieceValue = game.GetBoard()[x, y];
                    
                    var button = pieceButtons[x, y];
                    if (button != null)
                    {
                        button.Tag = index;
                        // 根据当前位置的值获取对应的图片
                        // pieceValue - 1 是因为图片索引从0开始，而board值从1开始
                        button.BackgroundImage = game.GetPieceImage(pieceValue - 1);
                        button.BackColor = Color.White;
                        
                                                 // 在自动演示期间，保持动画高亮效果
                         if (isAutoPlaying && isAnimating)
                         {
                             // 动画期间保持当前的高亮状态，不重置
                         }
                         // 保持选中状态的边框
                         else if (selectedPieceIndex == index)
                         {
                             button.FlatAppearance.BorderColor = Color.Red;
                             button.FlatAppearance.BorderSize = 3;
                         }
                         // 如果启用提示，高亮正确位置的碎片
                         else if (showHint && game.IsPieceInCorrectPosition(index))
                         {
                             button.FlatAppearance.BorderColor = Color.Green;
                             button.FlatAppearance.BorderSize = 2;
                         }
                         else
                         {
                             button.FlatAppearance.BorderColor = Color.Gray;
                             button.FlatAppearance.BorderSize = 1;
                         }
                    }
                }
            }
        }

        private void pauseButton_Click(object sender, EventArgs e)
        {
            if (game == null || game.CurrentState != PuzzleGame.GameState.Playing) return;
            
            isPaused = !isPaused;
            if (isPaused)
            {
                pauseButton.Text = "继续";
                gameTimer.Stop();
            }
            else
            {
                pauseButton.Text = "暂停";
                gameTimer.Start();
            }
        }

         private void shuffleButton_Click(object sender, EventArgs e)
         {
             if (game == null || game.CurrentState != PuzzleGame.GameState.Playing) return;
             
             // 重置选择状态
             selectedPieceIndex = -1;
             
             // 打乱拼图
             game.Shuffle();
             
             // 更新UI
             UpdatePieceButtons();
             
             // 重置计时器和步数
             gameTimer.Stop();
             gameTimer.Start();
             
             // 不显示打乱完成的提示，让用户专注于游戏
         }
 
         private void hintButton_Click(object sender, EventArgs e)
         {
             if (game == null) return;
             
             showHint = !showHint;
             hintButton.Text = showHint ? "隐藏提示" : "显示提示";
             hintButton.BackColor = showHint ? Color.LightPink : Color.LightCyan;
             
             if (showHint)
             {
                 UpdatePieceButtons();
             }
         }

         private void autoPlayButton_Click(object sender, EventArgs e)
         {
             if (game == null || game.CurrentState != PuzzleGame.GameState.Playing || isPaused) return;
             
             if (isAutoPlaying)
             {
                 // 停止自动演示
                 StopAutoPlay();
             }
             else
             {
                 // 开始自动演示
                 StartAutoPlay();
             }
         }

        private void settingsButton_Click(object sender, EventArgs e)
        {
            ShowSettingsDialog();
        }

        private void ShowSettingsDialog()
        {
            using (var settingsForm = new SettingsForm(soundEnabled, false, false, 3))
            {
                if (settingsForm.ShowDialog() == DialogResult.OK)
                {
                    soundEnabled = settingsForm.SoundEnabled;
                    // 这里可以添加其他设置的保存逻辑
                }
            }
        }

        private void leaderboardButton_Click(object sender, EventArgs e)
        {
            var leaderboardForm = new LeaderboardForm(leaderboard);
            leaderboardForm.ShowDialog();
        }

        private void exitButton_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("确定要退出游戏吗？", "确认退出", 
                MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                Application.Exit();
            }
        }

        private void difficultyComboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            // 难度改变时重置游戏
            if (game != null)
            {
                gameTimer.Stop();
                game = null;
                UpdateGameInfo();
                
                                 // 清除原图预览
                 originalImageBox.Image = null;
                 
                                  // 禁用游戏控制按钮
                  shuffleButton.Enabled = false;
                  pauseButton.Enabled = false;
                  hintButton.Enabled = false;
                  autoPlayButton.Enabled = false;
                
                // 清除拼图按钮
                if (pieceButtons != null)
                {
                    foreach (var button in pieceButtons)
                    {
                        if (button != null)
                            gamePanel.Controls.Remove(button);
                    }
                    pieceButtons = null;
                }
            }
        }

        protected override void OnFormClosing(FormClosingEventArgs e)
        {
            // 清理资源
            moveSound?.Dispose();
            completeSound?.Dispose();
            base.OnFormClosing(e);
        }

        #region 自动演示功能

                 private System.Windows.Forms.Timer autoPlayTimer;
         private List<(int, int)> solutionSteps;
         private int currentStepIndex = -1; // 当前演示步骤索引
         private bool isAnimating = false; // 是否正在执行动画
         private System.Windows.Forms.Timer flashTimer; // 闪烁效果计时器
         private bool flashState = false; // 闪烁状态

                 private void StartAutoPlay()
         {
             if (isAutoPlaying) return;
             
             isAutoPlaying = true;
             autoPlayButton.Text = "停止演示";
             autoPlayButton.BackColor = Color.Red;
             
             // 禁用其他按钮
             shuffleButton.Enabled = false;
             pauseButton.Enabled = false;
             hintButton.Enabled = false;
             
             // 生成解决方案
             GenerateSolution();
             
             // 创建自动演示计时器
             autoPlayTimer = new System.Windows.Forms.Timer { Interval = 3000 }; // 每3秒执行一步，给用户充足时间观察动画
             autoPlayTimer.Tick += AutoPlayTimer_Tick;
             autoPlayTimer.Start();
             
             // 不显示开始提示，让用户直接观察动画效果
         }

                 private void StopAutoPlay()
         {
             if (!isAutoPlaying) return;
             
                           isAutoPlaying = false;
                           autoPlayButton.Text = "自动演示";
               autoPlayButton.BackColor = Color.DarkBlue;
               autoPlayButton.ForeColor = Color.White;
             
             // 启用其他按钮
             shuffleButton.Enabled = true;
             pauseButton.Enabled = true;
             hintButton.Enabled = true;
             
             // 停止计时器
             autoPlayTimer?.Stop();
             autoPlayTimer?.Dispose();
             autoPlayTimer = null;
             
             // 停止闪烁效果
             StopFlashEffect();
             
             // 清除选择状态
             selectedPieceIndex = -1;
             UpdatePieceButtons();
             
             // 不显示停止提示，让用户专注于动画效果
         }

                 private void AutoPlayTimer_Tick(object sender, EventArgs e)
         {
             if (!isAutoPlaying || solutionSteps == null || solutionSteps.Count == 0)
             {
                 StopAutoPlay();
                 return;
             }
             
             if (isAnimating) return; // 如果正在执行动画，跳过
             
             // 执行下一步
             var step = solutionSteps[0];
             solutionSteps.RemoveAt(0);
             currentStepIndex++;
             
             // 开始动画：高亮显示要交换的两个方块
             StartSwapAnimation(step.Item1, step.Item2);
         }
         
         private void StartSwapAnimation(int index1, int index2)
         {
             isAnimating = true;
             
             // 高亮显示要交换的两个方块
             HighlightSwapPieces(index1, index2);
             
             // 开始闪烁效果
             StartFlashEffect(index1, index2);
             
             // 延迟执行交换，让用户看到高亮效果
             var animationTimer = new System.Windows.Forms.Timer { Interval = 2000 };
             animationTimer.Tick += (sender, e) =>
             {
                 animationTimer.Stop();
                 animationTimer.Dispose();
                 
                 // 停止闪烁效果
                 StopFlashEffect();
                 
                 // 执行交换
                 if (game.SwapPieces(index1, index2))
                 {
                     PlayMoveSound();
                     
                     // 重置交换方块的背景颜色为未选中状态
                     ResetSwapPiecesBackground(index1, index2);
                     
                     UpdatePieceButtons();
                     
                     // 检查是否完成
                     if (game.CheckCompletion())
                     {
                         StopAutoPlay();
                         PlayCompleteSound();
                         
                         MessageBox.Show($"自动演示完成！\n用时: {game.PlayTime:mm\\:ss}\n步数: {game.MoveCount}", 
                             "演示完成", MessageBoxButtons.OK, MessageBoxIcon.Information);
                     }
                 }
                 
                 isAnimating = false;
             };
             animationTimer.Start();
         }
         
         private void HighlightSwapPieces(int index1, int index2)
         {
             int size = game.GetBoard().GetLength(0);
             
             // 高亮第一个方块（绿色）
             int x1 = index1 % size;
             int y1 = index1 / size;
             if (pieceButtons[x1, y1] != null)
             {
                 pieceButtons[x1, y1].FlatAppearance.BorderColor = Color.Green;
                 pieceButtons[x1, y1].FlatAppearance.BorderSize = 5;
                 pieceButtons[x1, y1].BackColor = Color.LightGreen;
             }
             
             // 高亮第二个方块（红色）
             int x2 = index2 % size;
             int y2 = index2 / size;
             if (pieceButtons[x2, y2] != null)
             {
                 pieceButtons[x2, y2].FlatAppearance.BorderColor = Color.Red;
                 pieceButtons[x2, y2].FlatAppearance.BorderSize = 5;
                 pieceButtons[x2, y2].BackColor = Color.LightCoral;
             }
         }
         
         private void StartFlashEffect(int index1, int index2)
         {
             // 创建闪烁计时器
             flashTimer = new System.Windows.Forms.Timer { Interval = 200 }; // 每200毫秒闪烁一次
             flashTimer.Tick += (sender, e) => FlashSwapPieces(index1, index2);
             flashTimer.Start();
         }
         
         private void StopFlashEffect()
         {
             if (flashTimer != null)
             {
                 flashTimer.Stop();
                 flashTimer.Dispose();
                 flashTimer = null;
             }
         }
         
         private void FlashSwapPieces(int index1, int index2)
         {
             int size = game.GetBoard().GetLength(0);
             flashState = !flashState; // 切换闪烁状态
             
             // 闪烁第一个方块（绿色）
             int x1 = index1 % size;
             int y1 = index1 / size;
             if (pieceButtons[x1, y1] != null)
             {
                 if (flashState)
                 {
                     pieceButtons[x1, y1].FlatAppearance.BorderColor = Color.Lime;
                     pieceButtons[x1, y1].BackColor = Color.LimeGreen;
                     pieceButtons[x1, y1].FlatAppearance.BorderSize = 6;
                 }
                 else
                 {
                     pieceButtons[x1, y1].FlatAppearance.BorderColor = Color.Green;
                     pieceButtons[x1, y1].BackColor = Color.LightGreen;
                     pieceButtons[x1, y1].FlatAppearance.BorderSize = 5;
                 }
             }
             
             // 闪烁第二个方块（红色）
             int x2 = index2 % size;
             int y2 = index2 / size;
             if (pieceButtons[x2, y2] != null)
             {
                 if (flashState)
                 {
                     pieceButtons[x2, y2].FlatAppearance.BorderColor = Color.DarkRed;
                     pieceButtons[x2, y2].BackColor = Color.IndianRed;
                     pieceButtons[x2, y2].FlatAppearance.BorderSize = 6;
                 }
                 else
                 {
                     pieceButtons[x2, y2].FlatAppearance.BorderColor = Color.Red;
                     pieceButtons[x2, y2].BackColor = Color.LightCoral;
                     pieceButtons[x2, y2].FlatAppearance.BorderSize = 5;
                 }
             }
         }
         
         private void ResetSwapPiecesBackground(int index1, int index2)
         {
             int size = game.GetBoard().GetLength(0);
             
             // 重置第一个方块的背景颜色和边框
             int x1 = index1 % size;
             int y1 = index1 / size;
             if (pieceButtons[x1, y1] != null)
             {
                 pieceButtons[x1, y1].BackColor = Color.White;
                 pieceButtons[x1, y1].FlatAppearance.BorderColor = Color.Gray;
                 pieceButtons[x1, y1].FlatAppearance.BorderSize = 1;
             }
             
             // 重置第二个方块的背景颜色和边框
             int x2 = index2 % size;
             int y2 = index2 / size;
             if (pieceButtons[x2, y2] != null)
             {
                 pieceButtons[x2, y2].BackColor = Color.White;
                 pieceButtons[x2, y2].FlatAppearance.BorderColor = Color.Gray;
                 pieceButtons[x2, y2].FlatAppearance.BorderSize = 1;
             }
         }

        private void GenerateSolution()
        {
            solutionSteps = new List<(int, int)>();
            int size = game.GetBoard().GetLength(0);
            int totalPieces = size * size;
            
            // 获取当前状态
            int[,] currentBoard = (int[,])game.GetBoard().Clone();
            
            // 使用简单的贪心算法：将每个碎片移动到正确位置
            for (int targetValue = 1; targetValue <= totalPieces; targetValue++)
            {
                // 找到目标值当前的位置
                int currentX = -1, currentY = -1;
                for (int y = 0; y < size; y++)
                {
                    for (int x = 0; x < size; x++)
                    {
                        if (currentBoard[x, y] == targetValue)
                        {
                            currentX = x;
                            currentY = y;
                            break;
                        }
                    }
                    if (currentX != -1) break;
                }
                
                // 计算目标位置
                int targetX = (targetValue - 1) % size;
                int targetY = (targetValue - 1) / size;
                
                // 如果不在正确位置，需要移动
                if (currentX != targetX || currentY != targetY)
                {
                    // 找到目标位置当前的值
                    int targetCurrentValue = currentBoard[targetX, targetY];
                    
                    // 交换这两个位置
                    int currentIndex = currentY * size + currentX;
                    int targetIndex = targetY * size + targetX;
                    
                    solutionSteps.Add((currentIndex, targetIndex));
                    
                    // 更新模拟的棋盘状态
                    currentBoard[currentX, currentY] = targetCurrentValue;
                    currentBoard[targetX, targetY] = targetValue;
                }
            }
        }

        #endregion
    }
}